<template>
    <div id="add-edit-RiskZoning">
        <el-dialog
            :title="titleCon"
            v-model="isUseDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="60%" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="140px" :rules="rules">
                <el-row>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="风险分析单元名称" prop="v_Name">
                            <el-input v-model="ruleForm.v_Name" placeholder="请输入风险分析单元名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="所属风险分区" prop="v_RiskPartitionName">
                            <el-select 
                                filterable
                                class="m-2" 
                                placeholder="请选择所属风险分区" 
                                v-model="ruleForm.v_RiskPartitionName"
                                @change="areaChange"
                                value-key="id"
                            >
                                <el-option
                                    v-for="item in areaOption"
                                    :key="item.id"
                                    :label="item.v_Name"
                                    :value="item"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="风险评价方法" prop="d_PlanDate">
                            <el-select 
                                filterable
                                class="m-2" 
                                placeholder="请选择风险评价方法" 
                                v-model="ruleForm.v_EvaluationMethod" 
                            >
                                <el-option
                                    v-for="item in typeOption"
                                    :key="item.id"
                                    :label="item.value"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="风险分析单元类型">
                            <el-select 
                                filterable
                                class="m-2" 
                                placeholder="请选择风险分析单元类型" 
                                v-model="ruleForm.v_TypeName" 
                                @change="genreChange"
                                value-key="value"
                            >
                                <el-option
                                    v-for="item in genreOption"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="责任部门" prop="v_ResponsibleDepName">
                            <el-cascader 
                                v-model="ruleForm.l_ResponsibleDepId"
                                :options="orgOption" 
                                :props="orgProps" 
                                @change="orgChange"
                                filterable
                                clearable 
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="责任人" prop="v_ResponsibleMan">
                            <el-select 
                                filterable
                                class="m-2" 
                                placeholder="请选择负责人" 
                                v-model="ruleForm.v_ResponsibleMan" 
                            >
                                <el-option
                                    v-for="item in responsibleOption"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.name"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="风险等级">
                            <el-select 
                                filterable
                                class="m-2" 
                                placeholder="请选择风险等级" 
                                v-model="ruleForm.v_RiskLevelName" 
                                @change="levelChange"
                                value-key="value"
                            >
                                <el-option
                                    v-for="item in levelOption"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="是否启用">
                            <el-switch
                                v-model="ruleForm.isUse"
                                active-color="#07AAF9"
                                inactive-color="#FF5F33"
                                inline-prompt
                                active-text="启用"
                                inactive-text="禁用"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="ruleForm.n_Type === 0" :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="设备二维码">
                            <el-input @input="generateQRCode" v-model="ruleForm.v_DCQRCode" placeholder="请输入设备二维码" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="ruleForm.n_Type === 0" :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="生成二维码">
                            <img :src="qrDataURL" /> 
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">取 消</el-button>
                <el-button type="primary" :disabled="repeatDis" :loading="repeatDis" @click="submitForm(ruleFormRef)">提 交</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRef , toRefs , toRaw , onMounted , watch } from 'vue'
import { FormInstance, FormRules, ElButton, ElCol, ElDialog, ElForm, ElFormItem, ElInput, ElOption, ElRow, ElSelect } from 'element-plus'
import { sysOrgTree, sysEmpSelector } from '/@/api/centerControl/pubilc';
import { sysDictDataList , SMSDCAnalysisUnitAdd , SMSDCAnalysisUnitUpdate , SMSDCRiskPartitionList } from '/@/api/centerControl/sms';
import QRCode from 'qrcode';

/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    id?: Number,
    v_Name: String, // 风险分析单元名称
    n_Type: Number, // 风险分析单元类型
    v_TypeName: String, // 风险分析单元分类名称
    n_RiskLevel: Number, // 风险等级
    v_RiskLevelName: String, // 风险等级
    v_EvaluationMethod: String, // 风险评价方法
    l_ResponsibleDepId: Number, // 责任部门ID传给后端接口
    v_ResponsibleDepName: any, // 责任部门名称用于显示
    v_ResponsibleMan: String, // 责任人
    isUse: Boolean, // 是否启用
    l_RiskPartitionId: Number, // 所属风险分区
    v_RiskPartitionName: String, // 所属风险分区名称
    v_DCQRCode: String, // 设备二维码
}
export default defineComponent( {
    name: 'add-edit-RiskZoning',
    components: {},
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        }
    },
    setup(props,ctx){
        const titleCon = ref();
        const ruleFormRef = ref();
        const modeOption = ref();
        const typeOption = ref();
        const orgOption = ref();
        const areaOption = ref();
        const responsibleOption = ref();
        const qrDataURL = ref('');

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            // 分区名称
            v_Name: [
				{ required: true, message: '请输入风险分析单元名称', trigger: 'blur' },
			],
            // 责任部门
            v_ResponsibleDepName: [
				{ required: true, message: '请选择责任部门', trigger: 'change' },
			],
            // 责任人
            v_ResponsibleMan: [
				{ required: true, message: '请输入责任人', trigger: 'change' },
			],
            // 风险评价方法
            v_EvaluationMethod: [
                { required: true, message: '请选择风险评价方法', trigger: 'change' },
            ],
            // 所属风险分区
            v_RiskPartitionName: [
                { required: true, message: '请选择所属风险分区', trigger: 'change' },
            ],
            // 风险分析单元类型
            v_TypeName: [
                { required: true, message: '请选择风险分析单元类型', trigger: 'change' },
            ],
        })

        /*** 生成二维码 */
        const generateQRCode = (val: any) => {
            if(val){
                QRCode.toDataURL(val).then((url: any) => {
                    qrDataURL.value = url;
                }).catch((err: any) => {
                    console.error(err);
                });
            }else{
                qrDataURL.value = "";
            }
        }

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            ctx.emit('cancelUseClick')
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            ctx.emit('cancelUseClick')
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => { 
                if(valid){
                    let param = toRaw(state.ruleForm);
                    state.repeatDis = true;
                    try{
                        let res:any;
                        if(props.repairInfo === ''){
                            res = await SMSDCAnalysisUnitAdd(param);
                        }else{
                            res = await SMSDCAnalysisUnitUpdate(param);
                        }
                        if(res.success){
                            state.repeatDis = false;
                            ctx.emit('updateData');
                            ctx.emit('controlUseClick');
                        }else{
                            state.repeatDis = false;
                            ctx.emit('controlUseClick');
                        }
                    }catch(error){ state.repeatDis = false; }
                }else{
                    console.log('error submit!')
					return false
                }
            })
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }

        /*** getTree 获取组织架构树 */
        const getTree = async() => {
            let param = {}
            let res: any = await sysOrgTree(param);
            if(res.success) orgOption.value = res.data;
            
            let ras: any = await sysEmpSelector({});
            responsibleOption.value = ras.data;
        }

        /*** getDictFun 获取类型字典值 */
        const getDictFun = async() => {
            let param: any = {};
            param.TypeCode = 'SmsEvaluate';
            let res: any = await sysDictDataList(param);
            if(res.success) typeOption.value = res.data;

            let params:any = {};
            let ras: any = await SMSDCRiskPartitionList(params);
            if(ras.success) areaOption.value = ras.data;
        }

        /*** areaChange 风险分区改变事件 */
        const areaChange = (val: any) => {
            state.ruleForm.l_RiskPartitionId = val.id;
            state.ruleForm.v_RiskPartitionName = val.v_Name;
        }

        /*** orgChange 选择部门改变事件 */
        const orgChange = (val: any) => {
            if(val){
                let len = val.length;
                state.ruleForm.l_ResponsibleDepId = val[len - 1];
                state.ruleForm.v_ResponsibleDepName = val[len - 1];
            }
        }

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                // 状态数据重置
                state.repeatDis = false;
                qrDataURL.value = "";
                getDictFun();
                getTree();
                if(props.repairInfo !== ''){
                    titleCon.value = '编辑'
                    let getData = JSON.parse(props.repairInfo);
                    state.ruleForm = getData;
                    if(getData.v_DCQRCode) generateQRCode(getData.v_DCQRCode);
                }else{
                    titleCon.value = '新增';
                    state.ruleForm = {
                        v_Name: '', // 风险分析单元名称
                        n_Type: 0, // 风险分析单元类型
                        v_TypeName: '设备类', // 风险分析单元分类名称
                        n_RiskLevel: 0, // 风险等级
                        v_RiskLevelName: '', // 风险等级
                        v_EvaluationMethod: '', // 风险评价方法
                        l_ResponsibleDepId: 0, // 责任部门ID传给后端接口
                        v_ResponsibleDepName: '', // 责任部门名称用于显示
                        v_ResponsibleMan: '', // 责任人
                        isUse: true, // 是否启用
                        l_RiskPartitionId: 0, // 所属风险分区
                        v_RiskPartitionName: '', // 所属风险分区名称
                        v_DCQRCode: '', // 设备二维码
                    }
                }
            }
        })

        /*** genreChange 风险分析单元类型选择事件 */
        const genreChange = (val: any) => {
            console.log(val,'val')
            state.ruleForm.n_Type = val.value;
            state.ruleForm.v_TypeName = val.label;

        }

        /*** levelChange 风险等级选择事件 */
        const levelChange = (val: any) => {
            state.ruleForm.n_RiskLevel = val.value;
            state.ruleForm.v_RiskLevelName = val.label;
        }

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            isUseDialog,
            rules,
            modeOption,
            typeOption,
            orgProps: { checkStrictly: true , label: 'title', value: 'id', children: 'children' },
            orgOption,
            orgChange,
            genreOption: [
                {label: '设备类', value: 0},
                {label: '作业活动类', value: 1},
            ],
            genreChange,
            levelOption: [
                {label: '低风险', value: 0},
                {label: '一般风险', value: 1},
                {label: '较大风险', value: 2},
                {label: '重大风险', value: 3},
            ],
            levelChange,
            areaChange,
            areaOption,
            responsibleOption,
            qrDataURL,
            generateQRCode,
        }
    },
} )
</script>
<style scoped lang="scss">
    :deep(.el-cascader){
        width: 100%;
    }
    :deep(.el-select){
        width: 100%!important;
    }
    :deep(.el-input){
        width: 100%;
    }
</style>